<template>
  <div class="pending-review">
    <el-card class="box-card" v-for="api in pendingApis" :key="api.apiId">
      <div slot="header" class="clearfix">
        <span class="api-name">{{ api.name }}</span>
      </div>
      <el-steps :active="api.status === -1 ? 0 : (api.status === 0 ? 1 : 2)" align-center>
        <el-step title="待审核" :description="'申请时间: ' + formatTime(api.createtime)"></el-step>
        <el-step title="已审核" :description="api.status === 1 ? '审核成功时间: ' + formatTime(api.time) : '审核失败时间: ' + formatTime(api.time)" :status="api.status === 1 ? 'success' : 'error'"></el-step>
      </el-steps>
      <div class="api-info">
        <p v-if="api.status === 0"><strong>失败原因:</strong> {{ api.note }}</p>
      </div>
      <el-button type="primary" v-if="api.status === 1" @click="handlePublish(api)" class="publish-btn">发布</el-button>
      <el-button type="warning" v-if="api.status === 0" @click="handleReaudit(api)" class="reaudit-btn">再次审核</el-button>
    </el-card>

    <div v-if="pendingApis.length === 0" class="no-data">
      <el-empty description="暂无关于你的审核信息"></el-empty>
    </div>

    <el-dialog title="发布API" :visible.sync="dialogVisible" width="50%" class="publish-dialog">
      <el-form :model="publishForm" label-width="120px">
        <el-form-item label="发布类型">
          <el-select v-model="publishForm.type" placeholder="请选择发布类型" @change="handlePublishTypeChange">
            <el-option label="灰度发布" value="gray"></el-option>
            <el-option label="全量发布" value="full"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="请求阈值" v-if="publishForm.type === 'gray'">
          <el-input v-model.number="publishForm.threshold" placeholder="请输入请求阈值"></el-input>
        </el-form-item>
        <el-form-item label="请求延迟报警（毫秒）">
          <el-select v-model="publishForm.delayThreshold" placeholder="请选择请求延迟报警阈值">
            <el-option v-for="policy in apiAlarmPolicies" :key="policy.id" :label="policy.alarmpolicy" :value="policy.id"></el-option>
          </el-select>
        </el-form-item>
       
        <el-form-item label="API下架规则（告警）">
          <el-select v-model="publishForm.offThreshold" placeholder="请选择API下架规则阈值">
            <el-option v-for="policy in apiShutdownPolicies" :key="policy.id" :label="policy.policy" :value="policy.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="API防攻击配置">
          <el-input v-model="publishForm.attackProtection" placeholder="Hash_Base_Version_2.0.1" disabled></el-input>
        </el-form-item>
        <el-form-item label="Token生成规则">
          <el-input v-model="publishForm.tokenRule" placeholder="LanJing_SECURITY_@JVX32.4" disabled></el-input>
        </el-form-item>
        <el-form-item>
          <div class="publish-tips">
            <p><strong>灰度发布：</strong> 逐步将新版本API发布给部分用户，以验证其稳定性和性能。</p>
            <p><strong>全量发布：</strong> 将新版本API一次性发布给所有用户。</p>
            <p v-if="currentApi && currentApi.type === '自研'"><strong>推荐：</strong> 对于自研API，建议使用灰度发布以降低风险。</p>
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmPublish">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios';

export default {
  name: 'PendingReview',
  data() {
    return {
      pendingApis: [],
      dialogVisible: false,
      currentApi: null,
      publishForm: {
        type: '',
        threshold: null,
        delayThreshold: null,
        alertThreshold: null,
        offThreshold: null,
        attackProtection: 'Hash_Base_Version_2.0.1',
        tokenRule: 'LanJing_SECURITY_@JVX32.4'
      },
      apiAlarmPolicies: [],
      apiShutdownPolicies: []
    };
  },
  created() {
    this.fetchAuditList();
    this.fetchBasePolicies();
  },
  methods: {
    fetchAuditList() {
  axios.get('/api/system/auditList')
    .then(response => {
      if (response.data.code === 200) {
        console.log('获取审核列表成功', response.data.data);
        this.pendingApis = response.data.data.map(api => ({
          ...api,
          apiId: api.apiid.toString(), // 确保 apiId 是字符串类型
          name: ` ${api.name}`,
          description: ` ${api.note}`
        }));
      } else {
        this.$message.error('获取审核列表失败');
      }
    })
    .catch(error => {
      console.error('获取审核列表失败', error);
      this.$message.error('获取审核列表失败');
    });
},
    fetchBasePolicies() {
      axios.get('/api/system/basePolicy')
        .then(response => {
          if (response.data.code === 200) {
            this.apiAlarmPolicies = response.data.data.apiAlarmPolicies.map(policy => ({
              id: policy.id,
              alarmpolicy: policy.alarmpolicy,
              threshold: policy.threshold
            }));
            this.apiShutdownPolicies = response.data.data.apiShutdownPolicies.map(policy => ({
              id: policy.id,
              policy: policy.policy,
              threshold: policy.threshold
            }));
          } else {
            this.$message.error('获取基础策略失败');
          }
        })
        .catch(error => {
          console.error('获取基础策略失败', error);
          this.$message.error('获取基础策略失败');
        });
    },
    handlePublish(api) {
      this.currentApi = api;
      this.dialogVisible = true;
    },
    handleReaudit(api) {
      this.$confirm('确定要再次审核该API吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 模拟再次审核的逻辑
        this.$message({
          message: '再次审核请求已发送',
          type: 'success'
        });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消再次审核'
        });
      });
    },
    confirmPublish() {
      this.$confirm('确定要发布该API吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 构建发布数据对象
        const publishData = {
          apiId: this.currentApi.apiid,
          type: this.publishForm.type,
          threshold: this.publishForm.threshold,
          delayThreshold: this.publishForm.delayThreshold,
          alertThreshold: this.publishForm.alertThreshold,
          offThreshold: this.publishForm.offThreshold,
          attackProtection: this.publishForm.attackProtection,
          tokenRule: this.publishForm.tokenRule
        };
        console.log('发布数据', publishData);
        // 发送发布请求到后端
        axios.post('/api/system/publishApi', publishData)
          .then(response => {
            if (response.data.code === 200) {
              this.$message({
                message: 'API发布成功',
                type: 'success'
              });
              this.dialogVisible = false;
              this.fetchAuditList(); // 重新获取审核列表
            } else {
              this.$message.error('API发布失败');
            }
          })
          .catch(error => {
            console.error('API发布失败', error);
            this.$message.error('API发布失败');
          });
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消发布'
        });
      });
    },
    formatTime(time) {
      const date = new Date(time);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    handlePublishTypeChange(value) {
      if (value === 'gray') {
        // 模拟从后端获取请求阈值
        this.publishForm.threshold = 1000; // 假设默认阈值为1000
      } else {
        this.publishForm.threshold = null;
      }
    }
  }
};
</script>

<style scoped>
.pending-review {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  color: #2c3e50;
  padding: 20px;
}

.box-card {
  margin-bottom: 20px;
  border-radius: 10px;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.api-name {
  font-size: 1.2em;
  font-weight: bold;
}

.api-info {
  margin-top: 20px;
}

.el-steps {
  margin-top: 20px;
}

.publish-btn, .reaudit-btn {
  margin-top: 20px;
}

.publish-dialog {
  border-radius: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

.no-data {
  text-align: center;
  margin-top: 50px;
}

.publish-tips {
  margin-top: 20px;
  color: #606266;
}

/* 自定义已审核状态的颜色 */
.el-step__title.is-success {
  color: #67C23A; /* 绿色，表示审核成功 */
}

.el-step__title.is-error {
  color: #F56C6C; /* 红色，表示审核失败 */
}
</style>
